package E10;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static top.boking.E10.resuful.save.SaveDemo.null2String;

/**
 * @Author 史祥连
 * @Date 2023/12/8 12:35
 * @Version 1.0
 */
public class LoadAccessToken {
    /**
     * send request
     *
     * @param url
     * @param reqParam
     * @return
     * @throws Exception
     */
    public static String post(String url, Map reqParam) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // create httppost.
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            List nvps = new ArrayList();
            if (reqParam != null) {

                for (Object entry : reqParam.entrySet()) {
                    if (entry instanceof Map.Entry) {
                        Map.Entry s = (Map.Entry) entry;
                        nvps.add(new BasicNameValuePair((String) s.getKey(),(String) s.getValue()));
                    }
                }
            }
            UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(nvps, "utf-8");
            httppost.setEntity(reqEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new RuntimeException("request failed");
                } else {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        return EntityUtils.toString(entity, Charset.forName("UTF-8"));
                    }
                }
            } finally {
                response.close();
            }
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static String getAuthorizeCode() {
        // Authorized address
        String url = "https://weapp.yunteams.cn/oauth2/authorize";

        Map reqParam = new HashMap<>();
        // Registered company corp Id
        reqParam.put("corpid", "6caeb52680ecddf055e83508c2f84371");
        // The return type is fixed : code
        reqParam.put("response_type", "code");
        // After the redirection, the state parameter will be brought. The enterprise can fill in the parameter value of a-z A-Z 0-9, and the length cannot exceed 128 bytes.
        reqParam.put("state", "a896e2");
        try {
            String authorizeCode = post(url, reqParam);
            if (StringUtils.isNotBlank(authorizeCode)) {
                JSONObject authorizeCodeObj = JSONObject.parseObject(authorizeCode);
                return null2String(authorizeCodeObj.get("code"));
            } else {
                new Exception("authorizeCode generate exception");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    public static String getAccessToken() {
        // Authorized address
        String url = "https://weapp.yunteams.cn/oauth2/access_token";
        // get authorizeCode
        String authorizeCode = getAuthorizeCode();
        Map reqParam = new HashMap<>();
        reqParam.put("app_key", "c31767f0f4700bf6b098cdaafe2b5ac6");
        reqParam.put("app_secret", "53c2e529b572fc250b83748bee2afea5");
        reqParam.put("grant_type", "authorization_code");
        reqParam.put("code", authorizeCode);
        try {
            String accessToken = post(url, reqParam);
            if (StringUtils.isNotBlank(accessToken)) {
                JSONObject accessTokenObj = JSONObject.parseObject(accessToken);
                return null2String(accessTokenObj.get("accessToken"));
            } else {
                new Exception("accessToken generate exception");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        String accessToken = getAccessToken();
        System.out.println("accessToken = " + accessToken);
    }
}
